import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Req, Put } from '@nestjs/common';
import { AuthService } from './auth.service';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateRoleDto } from './dto/update-auth.dto';
import { UpdateUserDetailDto } from './dto/update-auth-detail.dto';
import { Public } from '../decorator/public.decorator';
import { Role } from '../decorator/roles.decorator'; // 导入角色装饰器
import { UserRole } from './entities/user.entity';
import { jwtAuth } from './jwt-auth.grard';
// 接口中使用ws
import { WsStartGateway } from '../websocket/ws.gateway';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly wsStartGateway: WsStartGateway
  ) { }
  // 测试
  @Get(':id')
  @Role(UserRole.Admin)
  findOne(@Param('id') id: string) {
    return this.authService.findOne(+id);
  }

  // 注册
  @Public()
  @Post("/signup")
  signup(@Body() signupData: CreateAuthDto) {
    return this.authService.signup(signupData)
  }

  // 登录
  @Public()
  @Post("/login")
  async login(@Body() loginData: CreateAuthDto) {
    // return this.authService.login(loginData);
    const result = await this.authService.login(loginData);
    if (result) {
      // 登录成功后触发 ws hello2
      this.wsStartGateway.hello2({ wstest: 'ws测试数据' }, null);
    }
    return result;
  }

  // 更新用户角色
  @Patch('/updateRole/:id')
  updateRole(
    @Param('id') id: number,
    @Body() role: UpdateRoleDto,
  ) {
    return this.authService.updateRole(id, role);
  }

  // 退出登录
  @Post('/logout')
  @UseGuards(jwtAuth)
  async logout(@Req() req: any) {
    const jwtPayload = req.user;
    return this.authService.logout(jwtPayload);
  }

  // 获取用户的详细信息
  @Get('/details/:userId')
  async getUserDetails(@Param('userId') userId: string): Promise<any> {
    return this.authService.getUserDetailById(userId);
  }
  // 更新用户的详细信息
  @Put('/details/:userId')
  async updateUserDetails(@Param('userId') userId: string, @Body() updateUserDetailDto: UpdateUserDetailDto): Promise<any> {
    return this.authService.updateUserDetailById(userId, updateUserDetailDto);
  }
  // 删除用户的详细信息
  @Delete('/details/:userId')
  async deleteDetails(@Param('userId') userId: string): Promise<any> {
    return this.authService.deleteUserDetailById(userId);
  }
}
